<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input v-model="listQuery.name" clearable class="filter-item" style="width: 200px;" placeholder="输入种子名称" />
      <el-button v-permission="['operation:seed:list']" class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查找</el-button>
      <el-button v-permission="['operation:seed:create']" class="filter-item" type="primary" icon="el-icon-edit" @click="handleCreate">添加</el-button>
      <el-button v-permission="['operation:seed:batchdelete']" :disabled="selectedIds.length === 0" class="filter-item" type="danger" icon="el-icon-delete" @click="handleBatchDelete">批量删除</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      size="small"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      @selection-change="handleSelectionChange"
    >

      <el-table-column align="center" type="selection" width="55" />
      <el-table-column align="center" label="ID" prop="id" />
      <el-table-column align="center" min-width="100" label="种子名称" prop="name" />
      <el-table-column align="center" min-width="100" label="预估最低产量(kg/m²)" prop="lowYield" />
      <el-table-column align="center" min-width="100" label="预估最高产量(kg/m²)" prop="highYield" />
      <el-table-column align="center" label="操作" width="250" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button v-permission="['operation:seed:edit']" type="primary" size="mini" @click="handleUpdate(scope.row,scope.$index)">编辑</el-button>
          <el-button v-permission="['operation:seed:delete']" type="danger" style="margin:5px" size="mini" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="listQuery.pageNo"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <el-tooltip placement="top" content="返回顶部">
      <back-to-top :visibility-height="100" />
    </el-tooltip>
    <el-dialog :visible.sync="attributeVisiable" title="种子管理">
      <el-form
        ref="attributeForm"
        :model="attributeForm"
        :rules="attrRules"
        :data = "attributes"
        status-icon
        label-position="left"
        label-width="150px"
        style="width: 500px; margin-left:50px;"
      >
        <el-form-item label="种子名称" prop="name">
          <el-input v-model="attributeForm.name" placeholder="请输入种子名称" />
        </el-form-item>
        <el-form-item label="预估最低产量" prop="lowYield" >
          <el-input v-model="attributeForm.lowYield" type="number" placeholder="请输入预估最低产量" />
        </el-form-item>
        <el-form-item label="预估最高产量" prop="highYield" >
          <el-input v-model="attributeForm.highYield" type="number" placeholder="请输入预估最高产量" />
        </el-form-item>
        <el-form-item label="图片" prop="imageUrl">
          <el-upload
            :action="uploadPath"
            :headers="headers"
            :on-success="handleimgsUrl"
            :on-error="handleErrorimgsUrl"
            :before-upload="beforeAvatarUpload"
            accept=".jpg, .jpeg, .png, .gif"
            list-type="picture"
            class="upload-img"
          >
            <div v-loading="loading" class="preimg" />
            <div v-show="attributeForm.imageUrl" :style="'background-image:url('+attributeForm.imageUrl+')'" class="preimg" />
            <i class="el-icon-plus" />
            <div slot="tip" class="el-upload__tip">只能上传jpg/jpeg/png/gif文件，且不超过2M</div>
          </el-upload>
          <el-input v-model="attributeForm.imageUrl" type="hidden" class="hidden-input" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="attributeVisiable = false">取消</el-button>
        <el-button type="primary" @click="handleAttributeAdd">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style>
  .hidden-input{
    display: block;
    width:0px;
    height:0px;
  }
  .el-upload--picture{
    position: relative;
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    cursor: pointer;
    line-height: 146px;
    vertical-align: top;
  }
  .el-upload-list--picture{
    display: none;
  }
  .upload-img .preimg{
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background-repeat:no-repeat;
    background-size:contain;
    background-position:center;
  }
  .el-loading-spinner{
    top:0;
  }
</style>
<script>
import { seedList, deleteSeed, batchDeleteSeed, createSeed, editSeed } from '@/api/seed'
import { uploadPath } from '@/api/storage'
import { getToken } from '@/utils/auth'
import BackToTop from '@/components/BackToTop'
import { MessageBox } from 'element-ui'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

export default {
  name: 'ParamList',
  components: { BackToTop, Pagination },
  data() {
    return {
      list: [],
      uploadPath,
      total: 0,
      listLoading: true,
      listQuery: {
        pageNo: 1,
        limit: 20,
        name: undefined
      },
      goodsDetail: '',
      detailDialogVisible: false,
      selectedIds: [],
      attributeVisiable: false,
      attributeForm: { name: '', lowYield: '', highYield: '', imageUrl: '' },
      loading: false,
      attrRules: {
        name: [
          { required: true, message: '种子名称不能为空', trigger: 'blur' }
        ],
        imageUrl: [
          { required: true, message: '图片不能为空', trigger: 'blur' }
        ]
      },
      attributes: [],
      editIndex: -1
    }
  },
  computed: {
    headers() {
      return {
        accessToken: getToken()
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      seedList(this.listQuery)
        .then(response => {
          this.list = response.data.data.items
          this.total = response.data.data.total
          this.listLoading = false
        })
        .catch(() => {
          this.list = []
          this.total = 0
          this.listLoading = false
        })
    },
    handleFilter() {
      this.listQuery.pageNo = 1
      this.getList()
    },
    handleCreate() {
      this.attributeForm = {}
      this.attributeVisiable = true
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除种子--' + row.name + '--, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteSeed(row.id)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            const index = this.list.indexOf(row)
            this.list.splice(index, 1)
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    handleBatchDelete(e) {
      // 执行批量删除
      this.$confirm('此操作将永久删除选中的' + this.selectedIds.length + '个种子, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batchDeleteSeed(this.selectedIds)
          .then(response => {
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
            this.getList()
          })
          .catch(response => {
            this.$notify.error({
              title: '失败',
              message: response.data.errmsg
            })
          })
      }).catch(() => {
        return false
      })
    },
    handleSelectionChange(e) {
      const temp = []
      e.forEach(item => {
        temp.push(item.id)
      })
      this.selectedIds = temp
    },
    handleUpdate(row, index) {
      this.attributeForm = row
      this.attributeVisiable = true
      this.editIndex = index
    },
    handleAttributeAdd() {
      this.$refs['attributeForm'].validate(valid => {
        if (valid) {
          const finalCont = {
            ...this.attributeForm
          }
          if (finalCont.id) {
            editSeed(finalCont)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
                this.list.splice(this.editIndex, 1, finalCont)
                this.attributeVisiable = false
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
                this.attributeVisiable = false
              })
          } else {
            createSeed(finalCont)
              .then(response => {
                this.$notify.success({
                  title: '成功',
                  message: '添加成功'
                })
                const temp = this.list
                temp.unshift(response.data.data)
                this.list = temp
                this.attributeVisiable = false
              })
              .catch(response => {
                MessageBox.alert('业务错误：' + response.data.errmsg, '警告', {
                  confirmButtonText: '确定',
                  type: 'error'
                })
                this.attributeVisiable = false
              })
          }
        }
      })
    },
    handleimgsUrl(response, file, fileList) {
      if (response.errno === 200) {
        this.attributeForm.imageUrl = response.url
        this.loading = false
      }
    },
    handleErrorimgsUrl(response, file, fileList) {
      this.$notify.error({
        title: '失败',
        message: '请重新上传图片'
      })
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 / 2 < 2
      this.loading = true
      if (!isLt2M) {
        this.$notify.error({
          title: '失败',
          message: '请重新上传2MB以内的图片'
        })
        this.loading = false
      }
      return isLt2M
    }
  }
}
</script>
